package com.bdqn.controler;

import com.alibaba.fastjson.JSON;
import com.bdqn.commom.Constants;
import com.bdqn.mapper.SysUserMapper;
import com.bdqn.pojo.Page;
import com.bdqn.pojo.SysUser;
import com.bdqn.pojo.TSysRole;
import com.bdqn.service.SysUserService;
import com.bdqn.service.TSysRoleService;
import com.mysql.cj.Session;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/user")
public class SysUserControler {
    private Logger logger = Logger.getLogger(SysUserControler.class);
    //用于返回查询到的用户数据
    private ArrayList<SysUser> queryList = new ArrayList<SysUser>();
    @Resource
    private SysUserService sysUserService;

    @Resource
    private TSysRoleService tSysRoleService;

    @PostMapping("/login")
    public String login(Model model, HttpSession session, @RequestParam String account, @RequestParam String password) {
        System.out.println("account:" + account + ",password:" + password);
        SysUser sysUser = sysUserService.getSysUserByAccount(account, password);
        if (sysUser == null) {
//            model.addAttribute("error","账号或密码错误");
//            return "login"; // 登录失败，跳转回登录页面
            throw new RuntimeException("账号或密码错误");
        }
        // 数据库账号密码匹配成功之后，将用户对象保存到Session作用域中
        session.setAttribute("USER_SESSION", sysUser);

        return "frame"; // 登录成功，跳转到后台页面
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        logger.debug("退出登录");
        // 清除当前登录用户的Session
        session.removeAttribute("USER_SESSION");
        session.invalidate(); // 销毁Session
        return "/login";
    }

    @GetMapping("")
    public String toFrom(HttpSession session) {
        logger.debug("跳转到后台主页");
        // 去到后台主页，但是必须是已经登录的用户
        if (session.getAttribute("USER_SESSION") == null) {
            return "redirect:/user/login";
        }
        return "frame";
    }

    @RequestMapping("/list")
    public String list(Model model, @RequestParam(required = false) String queryRealName, @RequestParam(required = false) Integer queryRoleId, @RequestParam(required = false, defaultValue = "1") int pageIndex) {
        logger.debug("查询用户列表");
        //页面查询条件数据回显
        model.addAttribute("queryRealName", queryRealName);
        model.addAttribute("queryRoleId", queryRoleId);

        //从服务层获取角色集合数据
        List<TSysRole> sysRolesList = tSysRoleService.selectSysRoleList(null);
        //将角色列表放入page作用域中
        model.addAttribute("roleList", sysRolesList);

        //页面查询过来的条件通过SysUser封装
        SysUser sysUser = new SysUser();
        sysUser.setRoleId(queryRoleId);
        sysUser.setRealName(queryRealName);

        //实例划分分页
        Page page = new Page();
        page.setTotalCount(sysUserService.getPageListTotal(sysUser)); //获取总记录数设置在分页中
        page.setCurrPageNo(pageIndex);  //当前页
        List<SysUser> pageList = sysUserService.getPageList(sysUser, page);
        //设置分页信息
        model.addAttribute("page", page);
        model.addAttribute("userList", pageList);
        return "sysUser/list";

    }

    @ResponseBody   //直接将数据响应(将返回的类容返回body区域)
    @DeleteMapping("/del/{userId}")
    public String del(@PathVariable("userId") int id) {
        int i = sysUserService.getDelete(id);
        System.out.println(1);
        System.out.println("删除失败" + i);
        if (i == 1) {
            System.out.println("删除成功");
            return "{\"delResult\":\"true\"}";
        } else {
            System.out.println(2);
            return "{\"delResult\":\"false\"}";
        }
    }

    @GetMapping("/toAdd")
    public String toAdd(HttpServletRequest request) {
        logger.debug("去到添加页面");
        List<TSysRole> list = tSysRoleService.selectSysRoleList(null);
        request.setAttribute("roleList", list);
        return "sysUser/add";
    }

    @ResponseBody  //将返回的类容返回body区域
    @GetMapping(value = "/userExist", produces = "text/html;charset=utf-8")
    public String userAccount(@RequestParam String account) {
        logger.debug("验证用户【account=" + account + "】是否存在");
        HashMap<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isEmpty(account)) {
            resultMap.put("exist", 1);
        } else {
            SysUser sysUser = sysUserService.getAccount(account);
            if (sysUser != null) {
                resultMap.put("exist", 1);  //账号以存在
            } else {
                resultMap.put("exist", 0);  //账号不存在
            }
        }
        return JSON.toJSONString(resultMap);
    }
    @PostMapping("/add")
    public String add(SysUser sysUser, HttpServletRequest request, HttpSession session, @RequestParam(value = "idPic",required = false)MultipartFile idPic,
                      @RequestParam(value = "workPic",required = false) MultipartFile workPic){
        //定义文件上传位置
        String uploadPath =request.getSession().getServletContext().getRealPath(Constants.UPLOAD_PATH);

        // 从上传的文件列表中获得第1个文件
        // MultipartFile idPic = attachs[0]; // 获得上传的证件照图片
        // 证件照图片文件上传，成功后返回地址
        String idPicPath = multipartFileUpload(uploadPath, request, idPic); // 调用文件上传方法，成功则返回上传地址
        if (idPicPath == null) {
            String uploadFileError = (String) request.getAttribute("uploadFileError");
            request.setAttribute("idPicUploadError", uploadFileError);
            request.removeAttribute("uploadFileError"); // 临时使用，使用完毕后移除信息
            return "sysUser/add";
        } else {
            // 设置身份证照片地址
            sysUser.setIdPicPath(idPicPath);

        }

        // 从上传的文件列表中获得第2个文件
        // MultipartFile workPic = attachs[1]; // 获得上传的工作照图片
        // 工作照图片文件上传，成功后返回地址
        String workPicPath = multipartFileUpload(uploadPath, request, workPic); // 调用文件上传方法，成功则返回上传地址
        if (idPicPath == null) {
            String uploadFileError = (String) request.getAttribute("uploadFileError");
            request.setAttribute("workPicUploadError", uploadFileError);
            request.removeAttribute("uploadFileError"); // 临时使用，使用完毕后移除信息
            return "sysUser/add";
        } else {
            // 设置工作证照片地址
            sysUser.setWorkPicPath(workPicPath);
        }

        // 设置操作者ID
        SysUser loginUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
        sysUser.setCreatedUserId(loginUser.getId());
        if (sysUserService.add(sysUser)) {
            return "redirect:/user/list";
        }
        return "sysUser/add";
    }

    /**
     * 多部件文件上传
     * @param uploadPath
     * @param request
     * @param multipartFile
     * @return
     */
    public String multipartFileUpload(String uploadPath,HttpServletRequest request,MultipartFile multipartFile){
        String uploadFilePath=null;  //文件上传地址，返回null表示失败
        //定义文件存放目录
        logger.debug("上传文件地址"+uploadPath);

        if(!multipartFile.isEmpty()){
            //获取文件上传的信息
            String originaFile = multipartFile.getOriginalFilename();  //源文件名称
            logger.debug("源文件名称为"+originaFile);
            String prefix = FilenameUtils.getExtension(originaFile);  //源文件后缀
            logger.debug("源文件后缀为"+prefix);
            long fileSize = multipartFile.getSize(); // 原文件大小
            logger.debug("上传文件大小：" + fileSize);

            // 判断上传的文件是否符合要求
            if (fileSize > Constants.MAX_FILE_SIZE) { // 上传文件大小不能超过500KB
                request.setAttribute("uploadFileError", " * 上传文件大小不得超过 500KB");
                return uploadFilePath;
            }
            if (!(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("pneg"))) {
                request.setAttribute("uploadFileError", " * 上传文件格式只能是jpg、jpeg、png、pneg");
                return uploadFilePath;
            }

            // 确定文件存储名称
            String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000) + "_Personal." + prefix;
            logger.debug("新生成的文件名为：" + fileName);

            // 将上传的文件保存到目标位置
            File targetFile = new File(uploadPath);
            if (!targetFile.exists()) {
                targetFile.mkdirs(); // 如果目录不存在则生成目录
            }
            // 保存文件
            try {
                // 存储物理地址 + 生成的文件名称
                multipartFile.transferTo(new File(targetFile, fileName));
            } catch (IOException e) {
                e.printStackTrace();
                request.setAttribute("uploadFileError", " * 文件上传失败！");
                return uploadFilePath;
            }
            // 文件上传完成就可以拿到地址
            uploadFilePath = File.separator + Constants.UPLOAD_PATH + File.separator + fileName;
        }

        // 返回文件上传成功后的地址，失败时返回null，并且将失败信息记录到
        return uploadFilePath;
    }

    /**
     * 查询用户详情
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/view/{id}")
    public String view(@PathVariable int id,Model model){
        logger.debug("根据id查询用户详情:"+id);
        SysUser sysUser = sysUserService.getId(id);
        model.addAttribute("sysUser",sysUser);
        return "sysUser/view";
    }

    /**
     * 跳转修改页面
     * @param uid
     * @param model
     * @return
     */
    @GetMapping("/toUpdate")
    public String update(@RequestParam int uid,Model model){
        logger.debug("根据id跳转修改页面:"+uid);
        SysUser sysUser = sysUserService.getId(uid);
        model.addAttribute(sysUser);
        return "sysUser/update";
    }

    /**
     * 执行修改操作
     */
    @PostMapping("/update")
    public String toUpdate(SysUser sysUser, HttpSession session){
        logger.debug("修改用户信息");
        SysUser sysUser1 = (SysUser) session.getAttribute(Constants.USER_SESSION);
        sysUser.setUpdatedUserId(sysUser1.getId());
        if(sysUserService.update(sysUser)){
            return "redirect:/user/list";
        }
        return "sysUser/update";
    }
}
